package com.linrui.gift.exception.handler;

import com.linrui.gift.exception.BusinessException;
import com.linrui.gift.exception.code.ErrorCode;
import com.linrui.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class UnifyExceptionHandler {
    //已知异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(e.getCode());
    }
    //jsr303
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult result = e.getBindingResult();
        //获取字段的异常
        List<FieldError> fieldErrorList = result.getFieldErrors();

        //把错误信息提取出来，然后拼接成信息
        StringBuilder stringBuilder = new StringBuilder();
        fieldErrorList.forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();
            stringBuilder.append(message+",");
        });

        String message = stringBuilder.substring(0,stringBuilder.length()-2);
        return AjaxResult.me().setSuccess(false).setMessage(message)
                .setCode(ErrorCode.ERROR_CODE_400.getCode());
    }

    //未知异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setMessage(ErrorCode.ERROR_CODE_500.getMassage())
                .setCode(ErrorCode.ERROR_CODE_500.getCode());
    }
}
